package com.example.v2.component.multids;

import com.example.v2.component.vault.VaultTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(
        basePackages = "com.example.v2.repository.baoxian",
        entityManagerFactoryRef = "entityManagerFactoryBaoxian",
        transactionManagerRef = "transactionManagerBaoxian")
public class BaoxianDataSourceConfiguration {

    @Resource
    private JpaProperties jpaProperties;
    @Resource
    private VaultTool vaultTool;
    @Value("${spring.datasource.baoxian.cipherText}")
    private String cipherText;


    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.baoxian")
    public DataSource dataSourceBaoxian() {
        String password = vaultTool.decrypt(cipherText);
        return DataSourceBuilder.create().password(password).build();
    }


    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBaoxian(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(dataSourceBaoxian())
                .packages(new String[]{"com.example.v2.model.entity.baoxian"})
                .properties(jpaProperties.getProperties())
                .persistenceUnit("baoxian")
                .build();
    }

    @Bean
    public PlatformTransactionManager transactionManagerBaoxian(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryBaoxian(builder).getObject());
    }


}
